package com.yixing.tech.entity.service;


import com.yixing.tech.common.base.BusinessException;
import com.yixing.tech.common.vo.s5.EntityVO;
import com.yixing.tech.entity.po.EntityData;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @author yixing tech
 * 实体处理钩子管理器
 */
@Component
public class EntityHookServiceManager implements ApplicationContextAware, EntityHookService {

    private final Map<String, AbstractEntityHookService> hookServiceMap = new HashMap<>();

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        ObjectProvider<AbstractEntityHookService> beanProvider = applicationContext.getBeanProvider(AbstractEntityHookService.class);
        beanProvider.stream().forEach(x -> hookServiceMap.put(x.getEntityId(), x));
    }


    @Override
    public EntityData beforeInsert(String tableId, EntityData data) throws BusinessException {
        AbstractEntityHookService hookService = hookServiceMap.get(tableId);
        if(hookService != null) {
            return hookService.beforeInsert(tableId, data);
        }
        return data;
    }

    @Override
    public EntityData afterInsert(String tableId, EntityData data) throws BusinessException {
        AbstractEntityHookService hookService = hookServiceMap.get(tableId);
        if(hookService != null) {
            return hookService.afterInsert(tableId, data);
        }
        return data;
    }

    @Override
    public void beforeDelete(String tableId, String entityId) throws BusinessException {
        AbstractEntityHookService hookService = hookServiceMap.get(tableId);
        if(hookService != null) {
            hookService.beforeDelete(tableId, entityId);
        }
    }

    @Override
    public void afterDelete(String tableId, String entityId) throws BusinessException {
        AbstractEntityHookService hookService = hookServiceMap.get(tableId);
        if(hookService != null) {
            hookService.afterDelete(tableId, entityId);
        }
    }

    @Override
    public EntityData beforeUpdate(String tableId, EntityData data) throws BusinessException {
        AbstractEntityHookService hookService = hookServiceMap.get(tableId);
        if(hookService != null) {
            return hookService.beforeUpdate(tableId, data);
        }
        return data;
    }

    @Override
    public EntityData afterUpdate(String tableId, EntityData oldData, EntityData newData) throws BusinessException {
        AbstractEntityHookService hookService = hookServiceMap.get(tableId);
        if(hookService != null) {
            return hookService.afterUpdate(tableId, oldData, newData);
        }
        return newData;
    }
}
